package cn.com.shopec.erp.provideinterface.commo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

@Component
public class WMSCallInterface {
    private static Log log = LogFactory.getLog(WMSCallInterface.class);

    @Resource(name = "WMSConfigMap")
    private Map<String, String> configMap;

    /**
     * @MethodName getReturnData
     * @Description ERP调用WMS接口公共方法
     * @param method
     *            调用WMS方法名
     * @return data 传送参数 JSON格式
     * @author gaoyaxiong
     * @date 2013-6-9 15:45:20
     */
    public String getReturnData(String method, String data) throws Exception {
        /*String appkey = this.configMap.get("appkey").toString(); // appkey
        String appsecret = this.configMap.get("appsecret").toString(); // appsecret
        String format = this.configMap.get("format").toString(); // 数据格式
        String urlStr = this.configMap.get("urlStr").toString(); // 服务地址
        String service = method + "?"; // 服务名
        String params = "appkey=" + appkey + "&appsecret=" + appsecret + "&format=" + format;
        // 传入参数
        params += "&data=" + data;*/
        StringBuffer result = new StringBuffer();
        HttpURLConnection conn = null;
        BufferedReader bufferedReader = null;
        StringBuffer fullUrl = new StringBuffer();
        fullUrl.append(this.configMap.get("urlStr").toString());
        fullUrl.append(method).append("?");
        fullUrl.append("appkey=").append(this.configMap.get("appkey").toString());
        fullUrl.append("&").append("appsecret=").append(this.configMap.get("appsecret").toString());
        fullUrl.append("&").append("format=").append(this.configMap.get("format").toString());
        fullUrl.append("&").append("data=").append(data);
        
        try 
        {
            //URL url = new URL(urlStr + service + params);// 获得url对象
            URL url = new URL(fullUrl.toString());// 获得url对象
            
            log.info(method + ":visit url is:" + url);
            
            conn = (HttpURLConnection) url.openConnection();
            
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setDoOutput(false);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");// 设置提交方法
            conn.setConnectTimeout(10000);//超过10秒请求没反应自动终止
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                    "UTF-8"));
            String line;
            
            while ((line = bufferedReader.readLine()) != null) 
            {
                result.append(line);
            }

           
        } 
        catch (Exception e) 
        {
            log.error(method + ": error is " + e.getMessage());
        }
        finally
        {
        	if(bufferedReader != null)
        	{
        		bufferedReader.close();
        	}
        	
        	if(conn != null)
        	{
        		conn.disconnect();
        		conn = null;
        	}
        }
        
        log.info("returned json string is:" + result);
        log.info(method+ " returned json string length is:" + result.length());

        return result.toString();
    }

    /**
     * 
     * @MethodName getReturnData
     * @Description 根据方法和参数集合调用WMS接口并获取返回数据
     * @author chengui
     * @date 2013-6-20 下午3:31:30
     * @param method
     * @param paramsMap
     * @return String
     * @throws Exception
     */
    public String getReturnData(String method, Map<String, String> paramsMap) throws Exception 
    {
        String urlStr = this.getCallUrl(method, paramsMap); // 服务地址
        log.info(method + ":visit url is:" + urlStr);
        StringBuffer result = new StringBuffer();
        BufferedReader bufferedReader = null;
        HttpURLConnection conn = null;
        
        try 
        {
            URL url = new URL(urlStr);// 获得url对象
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setDoOutput(false);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");// 设置提交方法
            conn.setConnectTimeout(10000);//超过10秒请求没反应自动终止
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                    "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) 
            {
                result.append(line);
            }
          
        } 
        catch (Exception e) 
        {
            log.error(method + " error is " + e.getMessage());
        }
        finally
        {
        	if(bufferedReader != null)
        	{
        		bufferedReader.close();
        	}
        	
        	if(conn != null)
        	{
        		conn.disconnect();
        		conn = null;
        	}
        }
        
        log.info(method+ " returned json string is:" + result);
        log.info(method+ " returned json string length is:" + result.length());
        
        return result.toString();
    }

    /**
     * 
     * @MethodName getCallUrl
     * @Description 拼调用路径
     * @author chengui
     * @date 2013-6-20 下午3:05:51
     * @param method
     * @param paramsMap
     * @return String
     * @throws Exception
     */
    private String getCallUrl(String method, Map<String, String> paramsMap) throws Exception {
        //String result = "";
    	StringBuffer result = new StringBuffer();
        /*String appkey = this.configMap.get("appkey").toString(); // appkey
        String appsecret = this.configMap.get("appsecret").toString(); // appsecret
        String format = this.configMap.get("format").toString(); // 数据格式
        String urlStr = this.configMap.get("urlStr").toString(); // 服务地址
        String service = method + "?"; // 服务名
        String params = "appkey=" + appkey + "&appsecret=" + appsecret + "&format=" + format;*/
        result.append(this.configMap.get("urlStr").toString());
        result.append(method).append("?");
        result.append("appkey=").append(this.configMap.get("appkey").toString());
        result.append("&").append("appsecret=").append(this.configMap.get("appsecret").toString());
        result.append("&").append("format=").append(this.configMap.get("format").toString());
        if (null != paramsMap && paramsMap.size() > 0) {
            for (String key : paramsMap.keySet()) {
                //params += "&" + key + "=" + paramsMap.get(key);
            	result.append("&").append(key).append("=").append(paramsMap.get(key));
            }
        }
        //result = urlStr + service + params;
        return result.toString();
    }

    // public static void main(String[] args) {
    // String method = "supplierCreateOrUpadte";
    // String data = "";
    // getReturnData(method,data);
    // }
    /**
     * 解析result
     * 
     * @return
     */
    public static boolean getResult(String result) throws Exception {
        JSONObject jsonObject = JSONObject.fromObject(result);
        return jsonObject.getBoolean("isSuccess");

    }
}
